package services

import (
	"bytes"
	"context"
	"crypto/tls"
	"encoding/json"
	"errors"
	"fmt"
	"github.com/sirupsen/logrus"
	"io"
	"net/http"
	"net/url"
	"strings"
	"time"
	"wecom_rebot/common"
	"wecom_rebot/core"
	"wecom_rebot/models"
)

var localSearchAccountLogger *logrus.Logger

// InitLocalSearchWithoutLogger 移除 init() 函数，改为显式初始化函数
func InitLocalSearchWithoutLogger() {
	// 确保在 common 初始化后调用
	localSearchAccountLogger = core.InitLogger(common.LogsErrorMap[15])
}

type HugeLocalSearchWithoutService struct {
}

func (s *HugeLocalSearchWithoutService) Handle(msgId int, subjectName, roomId string, content []string, jobId uint64) error {
	var msg = &models.Msg{}

	fmt.Println("localSearchAccountLogger", "原始结构Id：", msgId)
	// 获取数据
	err := common.DB.Where("id = ?", msgId).First(&msg).Error
	if err != nil {
		localSearchAccountLogger.Error("巨量本地推获取数据失败", common.LogsErrorMap[2], msgId, err)
		return err
	}

	localSearchAccountLogger.Info("localSearchAccountLogger", "原始结构：", content)

	// 处理需要的数据结构
	merchantId, accountId, err := s.analyzeContent(content)
	if err != nil {
		localSearchAccountLogger.Error(err)
		return err
	}

	// 移除功能行
	msg.Content = RemoveTitle(msg)
	localSearchAccountLogger.Info("localSearchAccountLogger", merchantId, "移除后的结构：", msg, "广告主信息：", content)

	rdb := core.InitRedis(13)
	ctx := context.Background()

	cookies, err := rdb.Get(ctx, "laravel_database_oead_adv_cookies").Result()

	fmt.Println("localSearchAccountLogger", "Cookies:", cookies)

	// 第四步 获取证件号码
	documentInfo, err := s.getDocumentNumber(merchantId, cookies)
	if err != nil {
		localSearchAccountLogger.Warnf("获取证件号码失败: %v", err)
		return errors.New("获取证件号码失败：" + err.Error())
	}

	// 第五步 查询直客信息
	searchResponse, err := s.getSearchWithout(documentInfo.Data.LifeAccountName, documentInfo.Data.LicenseNo, documentInfo.Data.LicenseType, cookies)
	if err != nil {
		if err.Error() == "" {
			encodedName := url.QueryEscape(documentInfo.Data.LifeAccountName)
			// 拼接完整的 URL
			sprintfUrl := fmt.Sprintf("https://web.disbursements.ecoremedia.net/#/other/account_industry?account_name=%s&media=oelocal&account_id=%s", encodedName, accountId)
			if err := BendiSendText(msg.Content+"\n-----------------------------------\n直客未存在情况，请点击链接手动设置行业"+"\n"+sprintfUrl, msg.RoomID, msg.Sender); err != nil {
				return errors.New("直客未存在情况，发送链接失败")
			}
			return nil
		}
		localCopyAccountLogger.Warnf("获取直客信息失败: %v", err)
		return err
	}

	// 组装直客信息
	DirectInfo := s.buildDirectInfoMessage(searchResponse)

	// 构建完整消息
	fullMessage := fmt.Sprintf("%s\n-----------------------------------\n%s", msg.Content, DirectInfo)

	// 发送消息
	err = BendiSendText(fullMessage, msg.RoomID, msg.Sender)
	if err != nil {
		localSearchAccountLogger.Errorf("发送联系人信息失败: %v", err)
		return err
	}

	return nil
}

// 构建联系人信息展示文本
func (s *HugeLocalSearchWithoutService) buildDirectInfoMessage(searchResponse *SearchWithoutResponse) string {
	var str strings.Builder

	str.WriteString("直客信息：\n")

	for _, item := range searchResponse.Data {
		str.WriteString(fmt.Sprintf("直客名称：%s\n直客ID：%d\n一二级行业：%s/%s\n", item.CustomerName, item.CustomerID, item.FirstIndustry, item.SmallIndustry))
	}

	return str.String()
}

// 获取直客信息
func (s *HugeLocalSearchWithoutService) getSearchWithout(customerName, licenseNo, licenseType, oeAdCookies string) (*SearchWithoutResponse, error) {
	sprintfUrl := fmt.Sprintf("https://agent.oceanengine.com/agent/adv-create/customer/query/?customerName=%s&isQianchuan=true&licenseNo=%s&licenseType=%s", customerName, licenseNo, licenseType)

	var response SearchWithoutResponse
	err := s.SendCurlRequest(sprintfUrl, nil, oeAdCookies, "GET", "", &response)
	if err != nil {
		localSearchAccountLogger.Errorf("获取直客信息失败: %v", err)
		return nil, err
	}

	// 记录完整响应
	localSearchAccountLogger.Infof("getSearchWithout获取直客完整信息: %+v", response)

	// 检查返回码不为0的情况
	if response.Code != 0 {
		localSearchAccountLogger.Warnf("getSearchWithout获取直客信息失败: %s", response.Msg)
		return nil, fmt.Errorf("接口返回错误: %s", response.Msg)
	}

	// 检查data为空的情况
	if len(response.Data) == 0 {
		localSearchAccountLogger.Warnf("getSearchWithout未找到对应的授权信息: %s", response.Msg)
		return nil, errors.New(response.Msg)
	}

	return &response, nil
}

// 获取证件号码
func (s *HugeLocalSearchWithoutService) getDocumentNumber(lifeAccountId, cookies string) (*DocumentNumberResponse, error) {
	numUrl := fmt.Sprintf("https://agent.oceanengine.com/agent/adv-create/localPromotion/query?lifeAccountId=%s", lifeAccountId)

	var req DocumentNumberResponse

	err := s.SendCurlRequest(numUrl, nil, cookies, "GET", "", &req)
	if err != nil {
		localSearchAccountLogger.Error("获取证件号码失败1", err)
		return nil, errors.New("获取证件号码失败1" + err.Error())
	}

	localSearchAccountLogger.Info("获取证件号码成功", req)

	if req.Code != 0 {
		localSearchAccountLogger.Error("获取证件号码失败2", req)
		return nil, fmt.Errorf("获取证件号码失败2: %s", req.Msg)
	}

	return &req, nil
}

// SendCurlRequest 发送HTTP请求
func (s *HugeLocalSearchWithoutService) SendCurlRequest(url string, postData interface{}, xhsCookies string, method string, oeCsrfToken string, result interface{}) error {
	// 创建请求上下文
	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()

	// 序列化POST数据
	var bodyReader io.Reader
	if postData != nil {
		jsonData, err := json.Marshal(postData)
		if err != nil {
			return fmt.Errorf("JSON序列化失败: %v", err)
		}
		bodyReader = bytes.NewBuffer(jsonData)
	}

	// 创建请求
	req, err := http.NewRequestWithContext(ctx, method, url, bodyReader)
	if err != nil {
		return fmt.Errorf("创建请求失败: %v", err)
	}

	// 设置请求头
	req.Header.Set("Content-Type", "application/json;charset=UTF-8")
	req.Header.Set("Cookie", xhsCookies)
	if oeCsrfToken != "" {
		req.Header.Set("Cg-Csrf-Token", oeCsrfToken)
	}

	// 创建自定义客户端
	client := &http.Client{
		Transport: &http.Transport{
			TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
		},
		// 禁用自动重定向
		CheckRedirect: func(req *http.Request, via []*http.Request) error {
			return http.ErrUseLastResponse // 不跟随重定向
		},
	}

	// 发送请求
	resp, err := client.Do(req)
	if err != nil {
		return fmt.Errorf("请求失败: %v", err)
	}
	defer resp.Body.Close()

	localSearchAccountLogger.Info("发送请求后得打印：", resp)
	// 读取响应体
	respBody, err := io.ReadAll(resp.Body)
	if err != nil {
		return fmt.Errorf("读取响应失败: %v", err)
	}

	localSearchAccountLogger.Info("获取后得参数格式：", string(respBody))

	if result != nil {
		if err := json.Unmarshal(respBody, &result); err != nil {
			return fmt.Errorf("JSON解析失败: %v", err)
		}
	}
	return nil
}

// analyzeContent 解析内容为广告主信息数组
func (s *HugeLocalSearchWithoutService) analyzeContent(content []string) (string, string, error) {
	// 初始化结果变量
	var merchantId string
	var accountId string

	// 遍历内容行
	for _, line := range content {
		// 商家账户ID
		if strings.HasPrefix(line, "商家账户ID:") {
			merchantId = strings.TrimSpace(strings.TrimPrefix(line, "商家账户ID:"))
		}
		// OA账户ID
		if strings.HasPrefix(line, "OA账户ID:") {
			accountId = strings.TrimSpace(strings.TrimPrefix(line, "OA账户ID:"))
		}
	}
	if merchantId == "" {
		localSearchAccountLogger.Warn("未解析到商家账户ID")
		return "", "", errors.New("解析参数失败: 缺少商家账户ID")
	}

	return merchantId, accountId, nil
}
